/*
 * All rights Reserved, Designed By DataDriver
 * Copyright:    DataDriver.Inc
 * Company:      Zhuo Wo Infomation Technology (ShangHai) CO.LTD
 */
package com.sun.pc;

import java.util.concurrent.TimeUnit;

/**
 * 生产者和消费者问题:
 * <p>
 * 多线程操作资源类时会出现混乱的现象：那么这个问题改则呢么解决呢？
 * 1、传统的Synchronized锁
 * 先明确两个概念: wait和sleep那个会携带锁： wait线程等待时会释放锁；sleep线程等待时会携带锁。
 */
public class B {

    public static void main(String[] args) {

          //线程的状态 Thread.State;
        /**
         *  NEW,  初始化状态
         *RUNNABLE, 运行状态
         *
         *BLOCKED, 阻塞状态
         *WAITING, 等待状态
         *
         *TIMED_WAITING, 超时等待
         *
         *TERMINATED;  终止状态
         */


        //Thread.sleep(); 线程休眠阻塞；使用的是Thread类
        // TimeUnit.SECONDS.sleep(4); 这个才是JUC包下的线程休眠方式



        Ticket2 ticket = new Ticket2();
        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        }, "C").start();
    }

}


/**
 * 线程操作资源类
 * <p>
 * 属性、方法
 */
class Ticket2 {

    private int num = 30;

    public synchronized void sale() {
        if (num != 0) {
            System.out.println(Thread.currentThread().getName() + "卖出票为:" + num-- + "剩余票:" + num);
        }
    }
}
